package com.example.noval.ui.page

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.noval.R
import com.example.noval.databinding.FragmentBookSearchBinding
import com.example.noval.db.mode.ContentResp
import com.example.noval.db.mode.SearchResp
import com.example.noval.db.mode.TocResp
import com.example.noval.network.repository.BookRepository
import com.example.noval.network.repository.SearchRepository
import com.example.noval.ui.adapter.SearchRecyclerAdapter
import com.example.noval.ui.adapter.decoration.LinearItemDecoration
import com.example.noval.ui.read.ReadActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.FormBody


/**
 * @Description
 * @Author zzl
 * @Date 2024/3/13
 */
class BookSearchFragment : Fragment(),OnClickListener {
   
   private var binding:FragmentBookSearchBinding?=null
   
   var adapter:SearchRecyclerAdapter?=null 
    
    var dataList:List<SearchResp>?=null
    
    var tocDataList:List<TocResp>?=null
    
    var recyclerView:RecyclerView?=null
    
    private val searchRepository by lazy { SearchRepository() }
    private val bookRepository by lazy { BookRepository() }
    var page: Int = 1
    var pageSize: Int = 20


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
            binding= FragmentBookSearchBinding.inflate(inflater, container, false)
        return binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding?.search?.setOnClickListener(this)
        recyclerView=binding?.recyclerView
        recyclerView?.layoutManager =LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        recyclerView?.addItemDecoration(LinearItemDecoration())
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.search->{
                search()
            }
        }
    }
    
    fun search(){
        var text:String= binding?.editText?.text.toString();
        GlobalScope.launch(Dispatchers.IO) {
            dataList=loadData(text)
            adapter=SearchRecyclerAdapter(dataList!!)
            adapter?.setOnItemClick(object :SearchRecyclerAdapter.OnItemClickListener{
                override fun onItemClick(position: Int) {
                    val searchResp = dataList!![position]
                    GlobalScope.launch (Dispatchers.IO){
                        val contents=loadBook(searchResp)
                        withContext(Dispatchers.Main){
                            val intent = Intent(activity, ReadActivity::class.java)
                            val bundle=Bundle()
                            bundle.putParcelableArrayList("contents",ArrayList(contents))
                            bundle.putParcelableArrayList("tocDataList",ArrayList(tocDataList))
                            intent.putExtras(bundle)
                            startActivity(intent)
                        }
                    }
                }
            })
            
            withContext(Dispatchers.Main) {
                Log.d("zzl",text)
                recyclerView?.adapter =adapter
            }
        }
    
    }
    
     suspend fun loadBook(searchResp: SearchResp):List<ContentResp> {
        tocDataList=searchRepository.searchToc(searchResp.bookId)
        val toc = tocDataList!![0]
        val content= bookRepository.searchContent(toc.bookId,toc.chapterId,toc.contentMd5)
         Log.d("zzl","tocs:$tocDataList")
         Log.d("zzl","content:$content")
        return content
     }
    
    suspend fun loadData(keyword:String): List<SearchResp>? {
        val requestBody = FormBody.Builder()
            .add("app", "midu")
            .add("device", "865166023475380")
            .add("keyword", keyword)
            .build()
        return searchRepository.searchBook(page,pageSize,keyword).apiData()
        
        
//        val request = Request.Builder()
//            .url("https://api.midukanshu.com/fiction/search/search")
//            .post(requestBody)
//            .build()
//
//        client.newCall(request)
//            .enqueue(object : Callback {
//                override fun onFailure(call: Call, e: IOException) {
//                    Log.d("zzl", e.toString())
//                }
//
//                override fun onResponse(call: Call, response: Response) {
//                    val responseData = response.body?.string()
//                    val jsonObject = JSONObject(responseData)
//                    val data = jsonObject.getString("data")
//                    val list = mutableListOf<String>(data)
//                    val array:String = JSONArray(list.get(0)).get(0).toString()
//                    val jsonObject1 = JSONObject(array)
//                    val book=Book()
//                    book.bookName=jsonObject1.getString("title")
//                    book.author=jsonObject1.getString("author")
//                    book.coverUrl=jsonObject1.getString("cover")
//                    book.intro=jsonObject1.getString("emDescription")
//                    
//                    
//                    Log.d("zzl", book.toString())
//                    
//                    
//                    
////                    val jsonObject = JSONObject(responseData)
////                    val value1 = jsonObject.getString("data")
////                    val data = mutableListOf<String>(value1)
////                    Log.d("zzl",data.get(0))
////                    val jsonObject1 = JSONArray(data.get(0))
////                    Log.d("zzl",jsonObject1.get(0).toString())
//
//
//
//                }
//            })
        
    }
    


}